<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/26
 * Time: 10:38
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\AuthRule;
use think\Controller;
use think\Exception;
use think\Request;

class Menu extends AdminBase
{
    /**
     * 初始化
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->auth = new AuthRule();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $menu = AuthRule::order('id asc')->select();
        $list = tree($menu);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加菜单页面
     * @return mixed
     */
    public function add()
    {
        $list      = AuthRule::select();
        $menu_list = tree($list);
        return $this->fetch('add', compact('menu_list'));
    }

    /**
     * 保存菜单页面数据
     * @param Request $request
     */
    public function save(Request $request)
    {
        $data     = $request->param('');
        $validate = $this->validate($data, 'Menu');
        if ($validate != true) {
            $this->error($validate);
        }
        $menu = AuthRule::create($data);
        if ($menu) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    /**
     * 编辑页面
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        $id = $request->param('id');
        $menu = AuthRule::select();
        $list = tree($menu);
        $menu = AuthRule::where(['id' => $id])->find();
        return $this->fetch('edit', compact('menu', 'list'));
    }

    /**
     * 更新
     * @param Request $request
     */
    public function update(Request $request)
    {
        $data = $request->param('');
        $validate = $this->validate($data, 'Menu');
        if($validate != true){
            $this->error($validate);
        }
        $info = $this->auth->save($data, ['id' => $data['id']]);
        if($info){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }

    public function del(Request $request)
    {
        $id = $request->param('id');
        $ids = $request->param('ids/a');
        try{
            if($ids){
                foreach($ids as $v){
                    $auth = AuthRule::destroy($v);
                }
            }else{
                $auth = AuthRule::destroy($id);
            }
            $this->success('删除成功');
        }catch(Exception $e){
            $this->error($e);
        }
        if($auth){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

}